/**
 * Created by LiH on 2017/12/22.
 */
import takeDefaultOptions from '../lib/takeDefaultOptions'
import ZCAlert from '../components/ZuicoolAlert'

let $vm;

export default {
  install(Vue){
    const Alert = Vue.extend(ZCAlert);

    if(!$vm){
      $vm = new Alert({
        el: document.createElement('div')
      });
      document.body.appendChild($vm.$el)
    }

    const defaults = takeDefaultOptions($vm);

    Vue.$ZCAlert = {
      show(options = {}){
        if(typeof options === 'string'){
          $vm.content = options
        } else if (typeof options === 'object') {
          options = Object.assign({}, defaults, options);
          for(let i in options){
            if(options.hasOwnProperty(i)){
              $vm[i] = options[i]
            }
          }
        }

        $vm.$off('confirm');
        $vm.$off('hide');
        $vm.$on('confirm', function () {
          options && options.onConfirm && options.onConfirm();
        });
        $vm.$on('hide', function () {
          options && options.onHide && options.onHide();
          $vm.visible = false;
        });
        $vm.visible = true
      },

      hide(){
        $vm.visible = false;
      }
    };

    Vue.mixin({
      created(){
        this.$ZCAlert = Vue.$ZCAlert
      }
    })
  }
}
